package com.gitee.wsl.io.api

interface ValueContainer:ValueReader,ValueWriter{}

inline fun <reified T:Any> ValueContainer.removeAndGet(key: String):T? = getOrNull(key,T::class)?.also { remove(key) }

inline fun <reified T:Any> ValueContainer.computeIfAbsent(key: String, value : T): T {
    getOrNull(key,T::class)?.let { return it }
    put(key,value)
    return value
}

inline fun <reified T:Any> ValueContainer.computeIfAbsent(key:String, block: () -> T): T{
    getOrNull(key,T::class)?.let { return it }
    val result = block()
    put(key,result)
    return result
}

inline fun <reified T:Any> ValueContainer.take(key:String) = getOrNull<T>(key)?.also{ removeAndGet<T>(key) }


inline fun <reified T:Any> ValueContainer.migrate(oldKey:String, newKey:String, defaultValue: T){
    val oldValue:T = getOrNull(oldKey, T::class)?:defaultValue
    put(newKey,oldValue)
    removeAndGet<T>(oldKey)
}